<?php


namespace app\mall\controller\Course;
use app\mall\controller\AppController;
use app\mall\model\Course\CourseCateRelationModel;
use app\mall\model\Course\CourseModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class Course extends AppController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getCourseList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = $param['page'];
        $limit = $param['limit'];
        $title = !empty($param['title']) ? $param['title'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        $is_del = !empty($param['is_del']) ? $param['is_del'] : "";
        $is_group = !empty($param['is_group']) ? $param['is_group'] : 0;
        array_push($where, ['is_group', '=', $is_group]);
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }
        array_push($where, ['mer_id', '=', $this->mall['id']]);
        if (!empty($title)) {
            array_push($where, ['title', 'like', '%' . $title . '%']);
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 1]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 0]);
            }
        }
        if (!empty($is_del)) {
            if ($is_del == 1) {
                array_push($where, ['is_del', '=', 0]);
            }
            if ($is_del == 2) {
                array_push($where, ['is_del', '=', 1]);
            }
        }
        $list = CourseModel::getCourseListWhere($page, $limit, $where);
        $count = CourseModel::getCourseCountWhere($where);
        foreach ($list as &$item){
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }


    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addCourse(Request $request)
    {
        $param = $request->param();

        $data = [
            'mer_id'    => $this->mall['id'],
            'title' => !empty($param['title']) ? $param['title'] : "",
            'teacher_brief' => !empty($param['teacher_brief']) ? $param['teacher_brief'] : "",
            'brief' => !empty($param['brief']) ? $param['brief'] : "",
            'price' => !empty($param['price']) ? $param['price'] : 0,
            'cost_price' => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'group_price' => !empty($param['group_price']) ? $param['group_price'] : 0,
            'group_num' => !empty($param['group_num']) ? $param['group_num'] : 0,
            'is_group' => !empty($param['is_group']) ? 1 : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'details' => !empty($param['details']) ? htmlspecialchars($param['details']) : "",
            'school_id' => !empty($param['school_id']) ? $param['school_id'] : 0,
            'deposit' => !empty($param['deposit']) ? $param['deposit'] : 0,
            'brief_group' => !empty($param['brief_group']) ? $param['brief_group'] : '',
            'up_time' => date("Y-m-d H:i:s",time()),
            'add_time' => date("Y-m-d H:i:s",time())
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "course/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "course/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }
        if (!empty($param['start_time'])) {
            $save['start_time'] = $param['start_time'];
        }
        if (!empty($param['end_time'])) {
            $save['end_time'] = $param['end_time'];
        }
        if (!empty($url)) {
            $data['img'] = $url;
        }
        if (!empty($urls)) {
            $data['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $data['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $data['is_del'] = 1;
        }

        Db::startTrans();
        try{
            $id = CourseModel::addCourse($data);
            if ($id) {
                if(!empty($param['select'])){
                    $cate_ids = explode(',',$param['select']);
                    $data = [];
                    foreach ($cate_ids as $cate_id){
                        $arr['course_id'] = $id;
                        $arr['cate_id'] = $cate_id;
                        $arr['add_time'] = date("Y-m-d H:i:s",time());
                        array_push($data,$arr);
                    }
                    $flag = CourseCateRelationModel::addCourseCateRelation($data);
                    if($flag){
                        DB::commit();
                        return Util::returnJson(self::CODE_SUCCESS, null, "添加成功");
                    }else{
                        DB::rollBack();
                        return Util::returnJson(self::CODE_ERROR, null, "添加失败3");
                    }
                }else{
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
                }
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "添加失败2");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败1");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editCourse(Request $request)
    {
        $param = $request->param();

        $save = [
            'mer_id'    => $this->mall['id'],
            'title' => !empty($param['title']) ? $param['title'] : "",
            'teacher_brief' => !empty($param['teacher_brief']) ? $param['teacher_brief'] : "",
            'brief' => !empty($param['brief']) ? $param['brief'] : "",
            'price' => !empty($param['price']) ? $param['price'] : 0,
            'cost_price' => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'group_price' => !empty($param['group_price']) ? $param['group_price'] : 0,
            'group_num' => !empty($param['group_num']) ? $param['group_num'] : 0,
            'is_group' => !empty($param['is_group']) ? 1 : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'details' => !empty($param['details']) ? htmlspecialchars($param['details']) : "",
            'school_id' => !empty($param['school_id']) ? $param['school_id'] : 0,
            'deposit' => !empty($param['deposit']) ? $param['deposit'] : 0,
            'brief_group' => !empty($param['brief_group']) ? $param['brief_group'] : '',
            'up_time' => date("Y-m-d H:i:s",time()),
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "course/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "course/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }
        if (!empty($param['start_time'])) {
            $save['start_time'] = $param['start_time'];
        }
        if (!empty($param['end_time'])) {
            $save['end_time'] = $param['end_time'];
        }
        if (!empty($url)) {
            $save['img'] = $url;
        }
        if (!empty($urls)) {
            $save['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $save['is_del'] = 1;
        }

        DB::startTrans();
        try{
            CourseModel::updateCourseWhere([['id', '=', $param['id']]], $save);
            if(!empty($param['select'])){
                //清除
                CourseCateRelationModel::delCourseCateRelationWhere([['course_id','=',$param['id']]]);
                $cate_ids = explode(',',$param['select']);
                $data = [];
                foreach ($cate_ids as $cate_id){
                    $arr['course_id'] = $param['id'];
                    $arr['cate_id'] = $cate_id;
                    $arr['add_time'] = date("Y-m-d H:i:s",time());
                    array_push($data,$arr);
                }
                $flag = CourseCateRelationModel::addCourseCateRelation($data);
                if($flag){
                    DB::commit();
                    return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
                }else{
                    DB::rollBack();
                    return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
                }
            }else{
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
        }
    }

    /**
     * 修改类型
     * @param Request $request
     * @return array
     */
    public function editCourseType(Request $request)
    {
        $param = $request->post();
        if (!empty($param['is_show'])) {
            if($param['is_show'] == "on"){
                $save['is_show'] = 1;
            }else{
                $save['is_show'] = 0;
            }
        }
        if (!empty($param['is_del'])) {
            if($param['is_del'] == "on"){
                $save['is_del'] = 1;
            }else{
                $save['is_del'] = 0;
            }
        }

        $flag = CourseModel::updateCourseWhere([['id', '=', $param['id']]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }
}
